package com.lk.pet.customers.controller;

import com.lk.pet.customers.dto.PetDetails;
import com.lk.pet.customers.dto.PetRequest;
import com.lk.pet.customers.exception.ResourceNotFoundException;
import com.lk.pet.customers.model.Owner;
import com.lk.pet.customers.model.Pet;
import com.lk.pet.customers.model.PetType;
import com.lk.pet.customers.repository.OwnerRepository;
import com.lk.pet.customers.repository.PetRepository;
import io.micrometer.core.annotation.Timed;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import java.util.List;
import java.util.Optional;

@RestController
@Timed("petclinic.pet")

@Slf4j
public class PetController {
    @Autowired
    private PetRepository petRepository;
    @Autowired
    private OwnerRepository ownerRepository;

    @GetMapping("petTypes")
    public List<PetType> getPetTypes(){
        return petRepository.findPetTypes();
    }


    @PostMapping("/owners/{ownerId}/pets")
    @ResponseStatus(HttpStatus.CREATED)
    public Pet processCreationForm(@PathVariable("ownerId") @Min(1) int ownerId,
                                   @RequestBody PetRequest petRequest) {

        final Optional<Owner> optionalOwner = ownerRepository.findById(ownerId);
        Owner owner = optionalOwner.orElseThrow(() -> new ResourceNotFoundException("Owner "+ownerId+" not found"));

        final Pet pet = new Pet();
        owner.addPet(pet);
        return save(pet, petRequest);
    }

    private Pet save(final Pet pet, final PetRequest petRequest) {

        pet.setName(petRequest.getName());
        pet.setBirthDate(petRequest.getBirthDate());
        petRepository.findPetTypeById(petRequest.getTypeId()).ifPresent(pet::setType);
        log.info("Saving pet{}",pet);
        return petRepository.save(pet);
    }

    @GetMapping("owners/*/pets/{petId}")
    public PetDetails findPet(@PathVariable("petId") Integer petId){
        return new PetDetails(findPetTypeById(petId));
    }

    private Pet findPetTypeById(Integer petId) {
        Optional<Pet> pet = petRepository.findById(petId);
        if (!pet.isPresent()){
            throw new ResourceNotFoundException("pet"+petId+"not found");
        }
        return pet.get();
    }
}
